
package com.ifcar.app.activity.topic;

import com.ifcar.app.activity.CommonFrameActivity;
import com.ifcar.app.activity.Splash;
import com.ifcar.app.activity.comment.CommentRankTabFragment;
import com.ifcar.app.activity.news.NewsListFragment;
import com.ifcar.app.activity.news.NewsListViewFragment;
import com.ifcar.app.adapter.TopicAdapter;
import com.ifcar.app.fragment.NRPullLoadingListFrament;
import com.ifcar.app.model.Topic;
import com.ifcar.app.util.BaseImageDownloader;
import com.ifcar.app.util.ModelUtils;
import com.ifcar.app.util.PicUtil;
import com.ifcar.app.util.StringUtil;
import com.ifcar.app.util.ThemeSettingsHelper;
import com.ifcar.app.util.Tools;
import com.ifcar.app.view.FitImageView;
import com.ifcar.app.view.LoadingListView;
import com.ifcar.app.activity.R;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 话题处理类
 * 
 * @author wjying
 */
public class TopicFragment extends NRPullLoadingListFrament implements OnItemClickListener,
        OnTouchListener {

    private TopicAdapter mAdapter;

    private List<Map<String, Object>> mData = new ArrayList<Map<String, Object>>();

    private List<Map<String, Object>> mAdatperData;

    private Map<String, Object> mFirstData;

    private View mHeaderLay;

    private BaseImageDownloader mImageDownloader;

    private int mTouchUpX;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRefreshTag("topic");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.pulllistview_topic, container, false);
    }

    @Override
    public void onTabSelected(boolean first) {
        
        super.onTabSelected(first);

        if (first) {
            startLoading();
        }

        if (mAdapter != null) {
            mAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onLoadingListViewAttached(LoadingListView loadingListView) {
        if (mHeaderLay == null) {
            LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
            mHeaderLay = layoutInflater.inflate(R.layout.topic_header_item_layout, null);
            FitImageView imageView = (FitImageView) mHeaderLay.findViewById(R.id.image);
            imageView.setRatio(((float) 176) / 458);
        }

        ListView listView = loadingListView.getListView();
        listView.addHeaderView(mHeaderLay);

        super.onLoadingListViewAttached(loadingListView);

        listView.setOnItemClickListener(this);
        listView.setOnTouchListener(this);

    }

    @Override
    public void onLoadingListViewDetached(LoadingListView loadingListView) {
        super.onLoadingListViewDetached(loadingListView);
        loadingListView.getListView().setOnTouchListener(null);
        loadingListView.getListView().setOnItemClickListener(null);
    }

    @Override
    public ListAdapter getAdapter() {
        return mAdapter;
    }

    @Override
    public boolean hasMoreView() {
        return false;
    }

    @Override
    protected void onLoading() {
        super.onLoading();

        // 加载本地数据,没有启用新线程
        List<Map<String, Object>> list = Topic.getCachedTopicList(getActivity());
        Message msg = getHandler().obtainMessage(MSG_LOADING);
        msg.obj = list;
        getHandler().dispatchMessage(msg);
    }

    @Override
    protected void onHandleLoading(Object result) {
        super.onHandleLoading(result);
        List<Map<String, Object>> list = (List<Map<String, Object>>) result;

        setData(list);

        if (mAdapter != null && mAdapter.getCount() > 0) {
            if (isNeedRefresh()) {
                getHandler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        refresh();
                    }
                }, 200);
            }
        } else {
            refresh();
        }

    }

    @Override
    protected void onRefreshing() {
        super.onRefreshing();
        callLoadingListViewStartLoading(mAdapter == null);
        final Context context = getActivity();
        new Thread() {
            public void run() {
                Message msg = getHandler().obtainMessage(MSG_REFRESHING);
                msg.obj = Topic.getTopicList(context);
                getHandler().sendMessage(msg);
            };
        }.start();
    }

    @Override
    protected void onHandleRefreshing(Object result) {
        super.onHandleRefreshing(result);
        List<Map<String, Object>> data = (List<Map<String, Object>>) result;

        if (mData.size() == 0 && (data == null || data.size() == 0)) {
            data = Topic.getDefaultTopicList();
        }

        if (data != null && data.size() != 0) {
            callLoadingListViewCompleteLoading(true, true);

            StringUtil.updateRefreshTime(getActivity(), getRefreshTag());

            setData(data);
        } else {
            Toast.makeText(getActivity(), R.string.msg_loading_failed, Toast.LENGTH_SHORT).show();
            callLoadingListViewCompleteLoading(false, true);
        }
    }

    private void setData(List<Map<String, Object>> data) {
        if (data != null && data.size() > 0) {
            removeVote(data);
            addCommentRank(data);
            mData.clear();
            mData.addAll(data);

            if (mImageDownloader == null) {
                mImageDownloader = new BaseImageDownloader(getActivity(), null);
                mImageDownloader.setRoundR(5);
                mImageDownloader.setMode(BaseImageDownloader.Mode.CORRECT);
                mImageDownloader.setThread(Thread.currentThread());
            }

            mFirstData = data.remove(0);

            if (mHeaderLay != null) {
                TextView name = (TextView) mHeaderLay.findViewById(R.id.name);
                name.setText((String) ModelUtils.getValue(mFirstData, Topic.PARAM_NAME));
                name.setTextSize(22);
                FitImageView image = (FitImageView) mHeaderLay.findViewById(R.id.image);

                BaseImageDownloader imageDownloader = new BaseImageDownloader(getActivity(), null);
                imageDownloader.setRoundR(5);
                imageDownloader.setMode(BaseImageDownloader.Mode.CORRECT);
                imageDownloader.setThread(Thread.currentThread());
                
                image.download(imageDownloader, (String) ModelUtils.getValue(mFirstData, Topic.PARAM_IMGSRC));
            }

            mAdatperData = data;

            mAdapter = new TopicAdapter(getActivity(), mAdatperData, mImageDownloader);

            if (getListView() != null) {
                getListView().setAdapter(mAdapter);
            }
        }
    }
    
    private void removeVote(List<Map<String, Object>> data) {
        if (!isAdded() || data == null || data.size() == 0) {
            return;
        }

        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
        if (sp.getBoolean("tab_vote", false)) {
            int voteIndex = -1;
            for (int i = data.size() - 1; i >= 0; i--) {
                Map<String, Object> info = data.get(i);
                if (Topic.TOPIC_VOTE.equals(ModelUtils.getValue(info, Topic.PARAM_REF))) {
                    voteIndex = i;
                    break;
                }
            }

            if (voteIndex != -1) {
                data.remove(voteIndex);
            }
        }
    }
    
    private void addCommentRank(List<Map<String, Object>> data) {
        if (!isAdded() || data == null) {
            return;
        }
        final Context context = getActivity();
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
        boolean isOlympic = sp.getBoolean("tab_olympic", true);
        if (isOlympic) {
            int bbsIndex = -1;
            for (int i = data.size() - 1; i >= 0; i--) {
                Map<String, Object> info = data.get(i);
                // 放在论坛后面
                if ("T1334130320521".equals(ModelUtils.getValue(info, Topic.PARAM_REF))) {
                    bbsIndex = i;
                    break;
                }
            }
            
            Map<String, Object> info = new HashMap<String, Object>();
            info.put(Topic.PARAM_NAME, getResources().getString(R.string.main_title_comment));
            info.put(Topic.PARAM_REF, CommentRankTabFragment.TAG);
            info.put(Topic.PARAM_IMGSRC, R.drawable.topic_comment_icon);
            if (bbsIndex == -1) {
                data.add(info);
            } else {
                data.add(bbsIndex + 1, info);
            }
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP) {
            mTouchUpX = (int) event.getX();
        }
        return false;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position == 0) {
            goToDetail(mFirstData);
            return;
        }

        position -= getListView().getHeaderViewsCount();
        if (mAdapter == null || position >= mAdapter.getCount()) {
            return;
        }

        List<Map<String, Object>> infos = mAdapter.getItem(position);
        if (infos == null) {
            return;
        }

        Map<String, Object> info = null;
        if (mTouchUpX > parent.getWidth() / 2) {
            info = infos.size() > 1 ? infos.get(1) : null;
        } else {
            info = infos.size() > 0 ? infos.get(0) : null;
        }

        if (info == null) {
            return;
        }

        goToDetail(info);
    }

    private void goToDetail(Map<String, Object> info) {
        String ref = (String) ModelUtils.getValue(info, Topic.PARAM_REF);
        if (TextUtils.isEmpty(ref)) {
            return;
        }
        String name = (String) ModelUtils.getValue(info, Topic.PARAM_NAME);

        Intent intent;
        if (Topic.TOPIC_ATTITUDE.equals(ref)) {
            intent = CommonFrameActivity.getStartIntent(getActivity(), name,
                    AttitudeListViewFrament.class, Topic.TOPIC_ATTITUDE, null);
        } else if (Topic.TOPIC_VOTE.equals(ref)) {
            intent = CommonFrameActivity.getStartIntent(getActivity(), name,
                    VoteWithTabFragment.class, Topic.TOPIC_VOTE, null);
        } else if (CommentRankTabFragment.TAG.equals(ref)) {
            intent = CommonFrameActivity.getStartIntent(getActivity(), name,
                    CommentRankTabFragment.class, CommentRankTabFragment.TAG, null);
        } else {
            Bundle bundle = new Bundle();
            bundle.putString(NewsListFragment.COLUMN_NAME, name);
            bundle.putString(NewsListFragment.COLUMN_ID, ref);
            bundle.putString(NewsListFragment.COLUMN_URL, ref);
            bundle.putBoolean(NewsListFragment.HEADER, true);
            intent = CommonFrameActivity.getStartIntent(getActivity(), name,
                    NewsListViewFragment.class, ref, bundle);
        }

        startActivity(intent);
    }

    @Override
    public void onApplyTheme() {

        ThemeSettingsHelper themeSettingsHelper = getThemeSettingsHelper();
        Context context = getActivity();
        
        if (mHeaderLay != null) {
            TextView nameTextView = (TextView) mHeaderLay.findViewById(R.id.name);
            themeSettingsHelper.setTextViewColor(context, nameTextView, R.color.top_text_color);
        }
    }
}
